package com.education.service.websocket;

import com.education.common.utils.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * webSocket消息处理器
 */
@Component
public class SystemWebSocketHandler implements WebSocketHandler {

    private static final Logger logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);

    private Map<String,WebSocketSession> sessionMap = new HashMap<>();

    /**
     * websocket连接就绪时调用
     * @param webSocketSession
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        logger.info("执行方法 afterConnectionEstablished");
        Map<String, Object> attributes = webSocketSession.getAttributes();
        String sessionId = (String) attributes.get("sessionId");
        if (!sessionMap.containsKey("sessionId")){
            //将websocket对象 存放到redis
            sessionMap.put(sessionId,webSocketSession);
        }
    }

    /**
     * 向客户端发送消息
     * @param sessionId
     * @param message
     */
    public void sendMessage(String sessionId,String message){
        WebSocketSession webSocketSession = sessionMap.get(sessionId);
        try{
            if (ObjectUtils.isNotEmpty(webSocketSession)) {
                webSocketSession.sendMessage(new TextMessage(message));
            }
        }catch (IOException e){
            logger.error("发送消息异常",e);
        }
    }


    /**
     * 用来处理客户端的消息推送
     * @param webSocketSession
     * @param webSocketMessage
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        logger.info("执行方法 handleMessage");
    }

    /**
     * 连接异常时调用
     * @param webSocketSession
     * @param throwable
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        logger.info("webSocket 连接异常");
    }

    /**
     * 关闭连接时调用
     * @param webSocketSession
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        logger.info("webSocket 关闭成功");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public void clearWebSocketSession(String sessionId){
        this.sessionMap.remove(sessionId); // 清除websocket session会话信息
    }
}
